package com.newegg.whois.util;

import java.util.HashMap;

public class WhoisParse {
	
	public static HashMap<String, Object> parse(String text) {
		HashMap<String, Object> result = new HashMap<>();
		String[] lines = text.split("\n");
		for (String l : lines) {
			String line = l.trim();
			boolean endLine = line.startsWith(">>>") && line.endsWith("<<<");
			if(endLine){
				line = line.replace(">>>", "").replace("<<<", "").trim();
			}
			if(line.indexOf(":") != -1){
				saveEntrty(result, line);
			}
			if(endLine){ break; }
		}
		return result;
	}
	
	static void saveEntrty(HashMap<String, Object> result, String line){
		String[] kv = line.split(":");
		if(kv.length >= 2 && kv[1] != null && !kv[1].trim().equals("")){
			String key = camelToUnderline(kv[0].trim());
			key = key.replace(">>>", "");
			if(key.startsWith("%") || key.indexOf(",") != -1){ return; }
			if(line.length() > line.indexOf(":")){
				String value = line.substring(line.indexOf(":") + 1).trim();
				if(value.length() < 50){
					result.put(key, value);
				}
			}else{
				result.put(key, "");
			}
		}
	}
	
	public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) { return ""; }
        String[] params = param.split(" ");
        StringBuffer buffer = new StringBuffer();
        for (String p : params) {
        	if(p.length() > 1){
        		buffer.append(p.substring(0, 1).toUpperCase()).append(p.substring(1).toLowerCase());
        	}else{
        		buffer.append(p.toLowerCase());
        	}
		}
        param = buffer.toString();
        return param.substring(0,1).toLowerCase() + param.substring(1);
    }

}
